//
//  CTDisplayView.m
//  TangQiao
//
//  Created by 宜必鑫科技 on 2017/10/11.
//  Copyright © 2017年 宜必鑫科技. All rights reserved.
//  主要思路就是由 NSAttributedString  -->  CTFramesetterRef -->  CTFrameRef CTFrameDraw
//  绘制图片是    CGContextDrawImage

#import "CTDisplayView.h"
#import "CoreTextImageData.h"
#import "CoreTextLinkData.h"
#import "CoreTextUtils.h"
#import <CoreText/CoreText.h>

@interface CTDisplayView ()<UIGestureRecognizerDelegate>
@property (strong,nonatomic)UIImageView *tapImgeView;
@property (strong,nonatomic)UIView *coverView;
@property (strong,nonatomic)UIWebView *webView;
@end


@implementation CTDisplayView

// drawRect调用是在Controller->loadView,，Controller->viewDidLoad 两方法之后调用的。
- (void)drawRect:(CGRect)rect
{
    [super drawRect:rect];
    // 如何简单的显示一个字体
    
    // 得到当前的画布
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    /* 翻转 应为底层的坐标原点是一左下角开始的  而 UIKIt是左上角 */
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextTranslateCTM(context, 0, self.bounds.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);

    if (self.data)
    {
        // 绘制文字 图片的位置使用空白符占用  然后在绘制图片
        CTFrameDraw(self.data.ctFrameRef, context);
        for (CoreTextImageData *imageData in self.data.imageArray)
        {
            UIImage *image = [UIImage imageNamed:imageData.name];
            CGContextDrawImage(context, imageData.imageRect, image.CGImage);
        }
    }
    
    debugLog(@"draw");
}

//初始化方法
-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupEvents];
    }
    return self;
}

//添加点击手势
-(void)setupEvents
{
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(userTapGestureDetected:)];
    tapRecognizer.delegate = self;
    [self addGestureRecognizer:tapRecognizer];
    self.userInteractionEnabled = YES;
}


//增加UITapGestureRecognizer的回调函数
/* 判断点击的点是否在图片和链接的位置上 点一次判断一次 */
-(void)userTapGestureDetected:(UITapGestureRecognizer *)recognizer
{
    // 点击的那个点
    CGPoint point = [recognizer locationInView:self];
    
    //点击图片
    for (CoreTextImageData *imagData in self.data.imageArray)
    {
        //翻转坐标系，因为ImageData中的坐标是CoreText的坐标系
        CGRect imageRect = imagData.imageRect;
        CGPoint imagePosition = imageRect.origin;
        imagePosition.y = self.bounds.size.height - imageRect.origin.y - imageRect.size.height;
        CGRect rect = CGRectMake(imagePosition.x, imagePosition.y, imageRect.size.width, imageRect.size.height);
        
        //检测点击图片的位置Point是否在rect之内
        if (CGRectContainsPoint(rect, point))
        {
            //在这里处理点击后的逻辑
            [self showTapImage:[UIImage imageNamed:imagData.name]];
            break;
        }
    }
    
    //点击链接
    CoreTextLinkData *linkData = [CoreTextUtils touchLinkInView:self atPoint:point data:self.data];
    if (linkData) {
        [self showTapLink:linkData.url];
        return;
    }
}

//显示图片
-(void)showTapImage:(UIImage *)tapImage
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    //图片
    _tapImgeView = [[UIImageView alloc] initWithImage:tapImage];
    _tapImgeView.frame = CGRectMake(0, 0, 300, 200);
    _tapImgeView.center = keyWindow.center;
        
    //蒙版
    _coverView = [[UIView alloc] initWithFrame:keyWindow.bounds];
    [_coverView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cancel)]];
    _coverView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6];
    _coverView.userInteractionEnabled = YES;
    
    [keyWindow addSubview:_coverView];
    [keyWindow addSubview:_tapImgeView];
}

-(void)cancel
{
    [_tapImgeView removeFromSuperview];
    [_coverView removeFromSuperview];
}

//显示链接网页
-(void)showTapLink:(NSString *)urlStr
{
    UIWindow *keyWindow = [UIApplication sharedApplication].keyWindow;
    
    //网页
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 300, 400)];
    _webView.center = keyWindow.center;
    [_webView setScalesPageToFit:YES];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    [_webView loadRequest:request];
    
    //蒙版
    _coverView = [[UIView alloc] initWithFrame:keyWindow.bounds];
    [_coverView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hide)]];
    _coverView.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.6];
    _coverView.userInteractionEnabled = YES;
    
    [keyWindow addSubview:_coverView];
    [keyWindow addSubview:_webView];
}

-(void)hide
{
    [_webView removeFromSuperview];
    [_coverView removeFromSuperview];
}





//对于一个复杂的排版页面
//1.配置类： 实现一些排版时使用的可配置项  如文字颜色，大小，行间距等等
//2.排版类： 实现w恩子内容的排版
//3.模型类： 用于保存显示需要的数据
//4.显示类： 负责显示内容，不负责排版

//    //这里你需要创建一个用于绘制文本的路径区域。
//    CGMutablePathRef path = CGPathCreateMutable();
////    CGPathAddRect(path, NULL, self.bounds);
//    CGPathAddEllipseInRect(path, NULL, self.bounds);
//
//    NSAttributedString *attString = [[NSAttributedString alloc]initWithString:@"I Love You很多时候，当你需要设计更高级的UI或者是减少设计师的工作量的时候，我们就需要用代码自行绘制UI，而自行绘制UI就需要用到CoreGraphics这个框架（OpenGL更高阶，目前还没达到这个水准）。"];
//    CTFramesetterRef framesetter = CTFramesetterCreateWithAttributedString((CFAttributedStringRef)attString);
//
//    // 在 framesetter 之后通过一个所选的文本范围（这里我们选择整个文本framesetter）与需要绘制到的矩形路径path创建一个帧。
//    CTFrameRef frame = CTFramesetterCreateFrame(framesetter, CFRangeMake(0, [attString length]), path, NULL);
//
//    // 绘制
//    CTFrameDraw(frame, context);
//
//    CFRelease(frame);
//    CFRelease(path);
//    CFRelease(framesetter);

//    if (self.data) {
//        CTFrameDraw(self.data.ctFrameRef, context);
//    }
@end






















